import axios from 'axios'
import { ElMessage } from 'element-plus'
import { handleError } from '@/utils/error-handler'

const request = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000
})

request.interceptors.request.use(
  config => {
    console.log('Request:', config.method.toUpperCase(), config.url, config.data || config.params)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  response => {
    console.log('Response:', response.data)
    const { code, message, data } = response.data || {}
    
    if (!response.data) {
      return Promise.reject(new Error('服务器响应格式错误'))
    }
    
    if (code === 200) {
      return data
    }
    
    return Promise.reject(new Error(message || '请求失败'))
  },
  error => handleError(error)
)

export default request 